package com.cjc.hotel.server.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjc.hotel.server.entity.TAdmin;
import com.cjc.hotel.server.entity.vo.AdminVo;
import com.cjc.hotel.server.handler.CommonException;
import com.cjc.hotel.server.result.Result;
import com.cjc.hotel.server.service.TAdminService;
import com.cjc.hotel.server.utils.ResultUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 后台登录控制器
 * @author chenjuncai
 */
@Controller
@RequestMapping("/admin/")
public class LoginController {
    @Autowired
    private TAdminService adminService;

    /**
     * 去登录页面
     * @return 结果
     */
    @GetMapping("toLogin")
    public String toLogin(){
        return "login";
    }
    /**
     * 去注册页面
     * @return 结果
     */
    @GetMapping("toRegister")
    public String toRegister(){
        return "register";
    }
    /**
     * 退出
     * @return 结果
     */
    @GetMapping("toLoginOut")
    public String toLoginOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return "redirect:/admin/toLogin";
    }
    /**
     * 登录
     * @return 结果
     */
    @ApiOperation("login")
    @PostMapping("login")
    @ResponseBody
    public Result<String> login(@Validated AdminVo adminVo, HttpServletRequest request){
        return adminService.login(adminVo,request);
    }
    /**
     * 注册
     * @return 结果
     */
    @ApiOperation("register")
    @PostMapping("register")
    @ResponseBody
    public Result<String> register(@Validated AdminVo adminVo){
        // 判断用户名是否重复
        QueryWrapper<TAdmin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("username",adminVo.getUsername());
        int count = adminService.count(adminQueryWrapper);
        if(count>0){
            throw new CommonException("用户名重复！");
        }
        return adminService.register(adminVo);
    }
}
